import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;


public class FileManager {
	public void createFolder(File folderFile) throws Exception {
		boolean success = folderFile.mkdir();
		if(success == false)
			throw new Exception("폴더가 존재하여 만들수 없습니다.");
	}
	public void move(File originFile, File targetFile) throws Exception{		
		validateMoveFile(originFile, targetFile);
		copyFile(originFile, targetFile);
		deleteFile(originFile);
	}
	
	public List<File> findFiles(File folderFile) throws Exception{
		validateFindFiles(folderFile);
		File[] allFiles = folderFile.listFiles();
		return selectFiles(allFiles);
	}
	
	
	
	
	private void validateFindFiles(File file) throws Exception {
		if(!file.exists())
			throw new Exception("폴더가 존재하지 않습니다.");
		if(!file.isDirectory())
			throw new Exception("정상적인 폴더가 아닙니다.");
	}

	private FileChannel getFileInputStreamChannel(File targetFile)
			throws FileNotFoundException {
		FileInputStream fis = new FileInputStream(targetFile);
		return fis.getChannel();
	}
	private FileChannel getFileOutputStreamChannel(File targetFile)
			throws FileNotFoundException {
		FileOutputStream fis = new FileOutputStream(targetFile);
		return fis.getChannel();
	}

	private void validateMoveFile(File originFile, File targetFile)
			throws Exception {
		if (!originFile.exists())
			throw new Exception("파일이 존재 하지 않습니다.");
		if (!originFile.isFile())
			throw new Exception("정상적인 파일이 아닙니다.");
		if (targetFile.exists())
			throw new Exception("파일이 존재 합니다.");
	}
	private void deleteFile(File originFile) throws Exception {
		boolean success = originFile.delete();
		if(!success)
			throw new Exception("파일이 삭제되지 않았습니다.");
	}
	private void copyFile(File originFile, File targetFile)
			throws FileNotFoundException, IOException, Exception {
		FileChannel originChannel = getFileInputStreamChannel(originFile);
		FileChannel targetChannel = getFileOutputStreamChannel(targetFile);
		
		long fileTransferSize = originChannel.transferTo(0, originChannel.size(), targetChannel);
		if(fileTransferSize != originChannel.size())
			throw new Exception("파일 복사가 정상적으로 이루어 지지 않았습니다.");
	}
	private List<File> selectFiles(File[] allFiles) {
		List<File> resultFiles = new ArrayList<File>();
		for (File file : allFiles) {
			if(file.isFile())
				resultFiles.add(file);
		}
		return resultFiles;
	}
		
}
